/*
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-05-09 17:49:57
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-05-12 20:29:41
 * @FilePath: /XMate-h5/src/composables/useWebSocket.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ref } from 'vue'
import { useWebSocket as vueUseWebSocket } from '@vueuse/core'
// @ts-ignore
import { getToken } from '@/utils/auth'
// @ts-ignore
import { getPlatform } from '@/utils/platformTool'
// @ts-ignore
import { SocketEventType } from '@/services/socketEvent'
import { isJson } from '@/utils/utils'
export interface WebSocketOptions {
  onMessage?: (eventType: string, eventData: any) => void
  autoReconnect?: boolean
}

export function useCustomWebSocket(options: WebSocketOptions = {}) {
  const { onMessage, autoReconnect = true } = options
  let ws: any

  const isConnected = ref(false)
  const lastError = ref<Event | null>(null)

  const connect = () => {
    const token = getToken()
    if (!token) {
      console.warn('token 为空，不进行websocket连接')
      setTimeout(connect, 2000)
      return
    }

    const socketUrl = (import.meta as any).env.VITE_XMATE_SOCKET_URL
    const url = `${socketUrl}?token=${token}&clientType=${getPlatform()}_${Date.now()}`

    ws = vueUseWebSocket(url, {
      autoReconnect,
      // heartbeat: true,
      onConnected(ws) {
        console.log('Connected', ws)
        isConnected.value = true
        ws.send('ping')
      },
      onDisconnected(ws, event) {
        console.log('Disconnected', event)
        isConnected.value = false
      },
      onError(ws, event) {
        console.error('Error', event)
        lastError.value = event
      },
      onMessage(ws, event) {
        try {
          const { data } = event
          console.log("onMessage", data);
          const parsedData = JSON.parse(data)
          const { endpoint: eventType, data: eventData } = parsedData

          // 直接将事件类型和数据传给使用方
          let parsedEventData = eventData;
          if (isJson(data)) {
            parsedEventData = JSON.parse(eventData)
          } 
          console.log("parsedEventData", parsedEventData);
          onMessage?.(eventType, parsedEventData)
        } catch (error) {
          console.error('解析消息失败:', error)
        }
      }
    })
  }

  const disconnect = () => {
    if (ws) {
      ws.close()
    }
  }

  return {
    connect,
    disconnect,
    isConnected,
    lastError
  }
} 